package com.malbbmsomanager.onlinereports;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
import com.malbbmsomanager.reports.DM_BBM_Items_Inquiry;
import com.malbbmsomanager.transactions.DM_BBM_InvoiceSalesOrder;
import com.malbbmsomanagerdemo.DM_BBM_InvoiceMenu;
import com.malbbmsomanagerdemo.R;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;

public class DM_BBM_Daily_Collection_Report_Online extends Activity
		implements ActionBar.OnNavigationListener {

	int count;
	JSONArray jsonArray;
	SimpleDateFormat originalFormatTxn = new SimpleDateFormat("dd-MM-yyyy");
	SimpleDateFormat targetFormatTxn = new SimpleDateFormat("yyyy-MM-dd");
	private SQLiteDatabase mydb;
	private static final String DATABASE_NAME = "dminvoicemanagerbbm.db";
	ProgressDialog mProgressDialog;
	ArrayList<HashMap<String, String>> arraylist;
	DM_BBM_Daily_Collection_Report_Online_Adapter adapter;
	BigDecimal AmountValue = new BigDecimal("0.00");
	BigDecimal AmountValueTotal = new BigDecimal("0.00");
	static String SoNo = "SoNo";
	static String InvoiceNo = "InvoiceNo";
	static String ReciptNo = "ReciptNo";
	static String Customer = "Customer";
	static String Amount = "Amount";

	ListView listview;
	String baseServerUrl, basePortVal, currentSalesRep, currentDatabase;
	String StrFromDate, StrToDate, StrPreName;
	TextView reporttotal;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_daily_collection_report_online);
		
		reporttotal = (TextView) findViewById(R.id.reporttotal);
		getConnectionUrl();
		getCurrentSalesRep();
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			StrFromDate = extras.getString("STARTFROMDATE");
			StrToDate = extras.getString("STARTTODATE");
		}
		new generateReportSummary().execute();
	}

	private class generateReportSummary extends AsyncTask<Void, Void, Void> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog = new ProgressDialog(
					DM_BBM_Daily_Collection_Report_Online.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Processing");
			// Set progressdialog message
			mProgressDialog
					.setMessage("Processing Daily Collection Sales Report...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {
				URL json = new URL(
						baseServerUrl
								+ "/PDADBWebServicebbM/PDADBWebServiceRest.svc/DailyCollectionReport/mobile123/"
								+ currentDatabase + "/" + StrFromDate + "/"
								+ StrToDate + "/" + currentSalesRep);
				Log.v("TAG", "XXXX URL  :" + json.toString());
				URLConnection jc = json.openConnection();
				BufferedReader readerfdblist = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));
				String line = readerfdblist.readLine();
				JSONObject jsonResponse = new JSONObject(line);
				jsonArray = jsonResponse
						.getJSONArray("DailyCollectionReportResult");
				arraylist = new ArrayList<HashMap<String, String>>();
				Log.v("TAG", "XXXXXXX 200 :" + arraylist.toString());
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject c = jsonArray.getJSONObject(i);
					HashMap<String, String> map = new HashMap<String, String>();

					map.put("SoNo", c.getString("SoNo")); // Name
					map.put("InvoiceNo", c.getString("InvoiceNo")); // Date
					map.put("ReciptNo", c.getString("ReciptNo")); // InvoiceNo
					map.put("Customer", c.getString("Customer")); // InvoiceNo
					
					AmountValue = new BigDecimal(c.getString("Amount"));
					AmountValue = AmountValue.setScale(2, BigDecimal.ROUND_HALF_UP);
					AmountValueTotal =  AmountValueTotal.add(AmountValue);
					map.put("Amount", "" + AmountValue);
					arraylist.add(map);
					count = count + 1;

				}
			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			Log.e(TAG, "Json Response :" + count);
			if (count < 1) {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_BBM_Daily_Collection_Report_Online.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("RECORDS NOT FOUND");
				// Setting Dialog Message
				alertDialog
						.setMessage("Records Not Found For Selected Date Range...");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			} else {
				reporttotal.setText("" + AmountValueTotal);
				listview = (ListView) findViewById(R.id.dmdailysalesonlinelist);
				// Pass the results into ListViewAdapter.java
				adapter = new DM_BBM_Daily_Collection_Report_Online_Adapter(
						DM_BBM_Daily_Collection_Report_Online.this,
						arraylist);
				// Binds the Adapter to the ListView
				listview.setAdapter(adapter);
			}
		}
	}

	private void getConnectionUrl() {
		// TODO Auto-generated method stub
		Cursor selectUrl = null;
		String selectUrlDetails;
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		selectUrlDetails = "SELECT serverurl,portval FROM serverinfo";
		selectUrl = mydb.rawQuery(selectUrlDetails, null);

		if (selectUrl != null) {
			if (selectUrl.getCount() > 0) {
				while (selectUrl.moveToNext()) {
					baseServerUrl = selectUrl.getString(0);
					basePortVal = selectUrl.getString(1);
				}
			}
		}
	}

	private void getCurrentSalesRep() {
		// TODO Auto-generated method stub
		Cursor selectUser = null;
		String selectUserDetails;
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);

		selectUserDetails = "SELECT username,serverDbName FROM usersettings";
		selectUser = mydb.rawQuery(selectUserDetails, null);

		if (selectUser != null) {
			if (selectUser.getCount() > 0) {
				while (selectUser.moveToNext()) {
					currentSalesRep = selectUser.getString(0);
					currentDatabase = selectUser.getString(1);
				}
			}
		}
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			LocationFound();
			return true;
		case R.id.action_refresh:
			// refresh
			/*
			 * refreshMenuItem = item; // load the data from server new
			 * SyncData().execute();
			 */
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void LocationFound() {
		// TODO Auto-generated method stub
		Intent i = new Intent(DM_BBM_Daily_Collection_Report_Online.this,
				DM_BBM_Online_Report_Generator.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(i);
		finish();
		return;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
	}
}
